import { useState, useEffect, forwardRef, useImperativeHandle } from 'react'
import { Form, Input, Tree } from 'antd'
import type { TreeDataNode, TreeProps } from 'antd'

const FormConfig = forwardRef(
    (props: { treeData: TreeDataNode[]; editable?: boolean }, ref) => {
        const { treeData, editable } = props
        const [form] = Form.useForm()
        const [checkedKeys, setCheckedKeys] = useState<string[]>([])
        const [type, setType] = useState('') // 新增角色 or 分配权限

        useImperativeHandle(ref, () => ({
            setFieldsValue: (values: any) => {
                form.setFieldsValue(values)
                setCheckedKeys(values.roleList || [])
                setType(values.type || '')
            },
            submit: () => form.validateFields(),
            reset: () => {
                form.resetFields()
                setCheckedKeys([])
            },
        }))

        // Tree 勾选变化时同步表单
        const onCheck: TreeProps['onCheck'] = (checked, info) => {
            const keys = Array.isArray(checked) ? checked : checked.checked
            setCheckedKeys(keys)
            form.setFieldsValue({ roleList: keys })
        }

        return (
            <Form
                form={form}
                name="basic"
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
                autoComplete="off"
                layout="horizontal"
            >
                <Form.Item
                    label="角色名"
                    name="name"
                    rules={[{ required: true, message: '请输入用户名' }]}
                >
                    <Input disabled={editable} />
                </Form.Item>
                <Form.Item
                    label="权限树"
                    name="roleList"
                    rules={[{ required: true, message: '请选择' }]}
                >
                    <Tree
                        checkable
                        checkedKeys={checkedKeys}
                        defaultExpandAll
                        onCheck={onCheck}
                        treeData={treeData}
                        fieldNames={{ title: 'label' }}
                    />
                </Form.Item>
                <Form.Item label="描述" name="description">
                    <Input.TextArea rows={4} placeholder="请输入描述" />
                </Form.Item>
                <Form.Item name="id" hidden>
                    <Input />
                </Form.Item>
            </Form>
        )
    }
)

export default FormConfig
